package com.mysoft.gfyx.common.rpc.opptyservice.impl;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.gfyx.common.concurrency.CacheAgentService;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.TenantUserInfoDto;
import feign.RequestInterceptor;
import feign.RequestTemplate;

import java.util.Date;

public class OpptyServiceRequestInterceptorImpl implements RequestInterceptor {
    protected String host;
    protected String appCode;
    protected String iss;
    protected String secret;
    protected CacheAgentService cacheAgentService;

    protected ContextManager contextManager;

    public OpptyServiceRequestInterceptorImpl(String host, String appCode, String iss, String secret, CacheAgentService cacheAgentService, ContextManager contextManager) {
        this.host = host;
        this.appCode = appCode;
        this.iss = iss;
        this.secret = secret;
        this.cacheAgentService = cacheAgentService;
        this.contextManager = contextManager;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("authorization", this.generateJWT());
        requestTemplate.header("tenant_code", contextManager.fetchContextInfo().getTenantCode());
        requestTemplate.header("user_info", this.assembleUserInfo());
    }

    private String generateJWT() {
        // 1.先从缓存获取token,获取不到则重新生成,并保存到缓存
        String cacheKey = "gfyx:oppty-service:token";
        String token = cacheAgentService.getCachedData(cacheKey);
        if (token != null && !token.equals("")) {
            return "bearer " + token;
        }

        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 3600 * 1000;//有效时间60分钟
        Date expTime = new Date(currentTime);
        String appCode = this.appCode;
        String secret = this.secret;
        String iss = this.iss;

        token = JWT.create()
                .withClaim("a", appCode)
                .withClaim("e", "")
                .withIssuedAt(start)
                .withExpiresAt(expTime)
                .withIssuer(iss)
                .sign(Algorithm.HMAC256(secret));
        //有效期1小时,缓存3500秒
        cacheAgentService.setCacheDataAndSetExpiredTime(cacheKey, token, 3500);
        return "bearer " + token;
    }

    private String assembleUserInfo() {
        TenantUserInfoDto userInfoDto = new TenantUserInfoDto();
        userInfoDto.setTenant_code(contextManager.fetchContextInfo().getTenantCode());
        userInfoDto.setUser_code(contextManager.fetchContextInfo().getUserContext().getUserCode());
        userInfoDto.setUser_name(contextManager.fetchContextInfo().getUserContext().getUserName());
        userInfoDto.setMobile_phone(contextManager.fetchContextInfo().getUserContext().getMobilePhone());
        userInfoDto.setTenant_user_uid(contextManager.fetchContextInfo().getUserContext().getUserId().toString());

//        System.out.println(JSON.toJSONString(userInfoDto));
        return JSON.toJSONString(userInfoDto);
    }
}